package com.yangluyao.jsr303.hibernate.validator.controller;

import com.yangluyao.jsr303.hibernate.validator.common.Rest;
import com.yangluyao.jsr303.hibernate.validator.common.impl.HttpResult;
import com.yangluyao.jsr303.hibernate.validator.model.User;
import com.yangluyao.jsr303.hibernate.validator.service.IUserService;
import com.yangluyao.jsr303.hibernate.validator.valid.SaveValidated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author YLY
 * @ClassName JSR303Controller
 * @Date 2020/7/29
 * @Version 1.0.2
 */
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/user")
    public Rest findUsers() {
        List<User> users = userService.findUsers();
        return HttpResult.ok(users, "查询成功", 200);
    }

    @GetMapping("/user/{id}")
    public Rest findUserById(@PathVariable("id") Long id) {
        User user = userService.findUserById(id);
        return HttpResult.ok(user, "查询成功", 200);
    }

    @GetMapping("/user/name/{id}")
    public Rest findUserName(@PathVariable("id") Long id) {
        String userName = userService.findUserName(id);
        return HttpResult.ok(userName, "查询成功", 200);
    }

    /**
     * jsr303 可以使用group分组进行校验
     * @param user
     * @return
     */
    @PostMapping("/user")
    public Rest saveUser(@Validated(SaveValidated.class) User user) {
        User user1 = userService.saveUser(user);
        return HttpResult.ok(user1, "保存成功", 200);
    }


}
